﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;

namespace YJKRevitStairs.StairsModel
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdStairBeamMerge : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string messages, ElementSet elements)
		{
			Document document = cmdData.Application.ActiveUIDocument.Document;
			Selection selection = cmdData.Application.ActiveUIDocument.Selection;
			Result result;
			for (;;)
			{
				IList<Element> list = null;
				try
				{
					BeamFilter beamFilter = new BeamFilter();
					list = selection.PickElementsByRectangle(beamFilter, "请选择两根首尾相连的梯梁");
				}
				catch
				{
					result = Autodesk.Revit.UI.Result.Succeeded;
					break;
				}
				if (2 == list.Count)
				{
					LocationCurve locationCurve = (list[0] as FamilyInstance).Location as LocationCurve;
					Curve curve = locationCurve.Curve;
					XYZ endPoint = curve.GetEndPoint(0);
					XYZ endPoint2 = curve.GetEndPoint(1);
					FamilyInstance familyInstance = list[1] as FamilyInstance;
					Curve curve2 = (familyInstance.Location as LocationCurve).Curve;
					XYZ endPoint3 = curve2.GetEndPoint(0);
					XYZ endPoint4 = curve2.GetEndPoint(1);
					Transaction transaction = new Transaction(document, "StairBeamMerge");
					transaction.Start();
					if (endPoint.IsAlmostEqualTo(endPoint3))
					{
						locationCurve.Curve = Line.CreateBound(endPoint2, endPoint4);
						document.Delete(familyInstance.Id);
					}
					else if (endPoint.IsAlmostEqualTo(endPoint4))
					{
						locationCurve.Curve = Line.CreateBound(endPoint3, endPoint2);
						document.Delete(familyInstance.Id);
					}
					else if (endPoint2.IsAlmostEqualTo(endPoint3))
					{
						locationCurve.Curve = Line.CreateBound(endPoint, endPoint4);
						document.Delete(familyInstance.Id);
					}
					else if (endPoint2.IsAlmostEqualTo(endPoint4))
					{
						locationCurve.Curve = Line.CreateBound(endPoint, endPoint3);
						document.Delete(familyInstance.Id);
					}
					transaction.Commit();
				}
			}
			return result;
		}
	}
}
